package com.sdl3.core;

import com.sdl3.event.PineaEvent;
import com.sdl3.render.PineaColor;
import com.sdl3.render.PineaImage;
import com.sdl3.render.SDLPineaImage;
import com.sdl3.shape.PineaRect;
import com.sun.jna.Native;
import com.sun.jna.Pointer;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class Pinea {

    public static final int PINEA_EVENT_KEY_UP = 0x301;
    public static final int PINEA_EVENT_KEY_DOWN = 0x300;
    public static final int PINEA_EVENT_QUIT = 0x100;

    public static final int PINEA_KEY_A = 0x00000061;
    public static final int PINEA_KEY_D = 0x00000064;
    public static final int PINEA_KEY_W = 0x00000077;
    public static final int PINEA_KEY_S = 0x00000073;
    public static final int PINEA_KEY_SPACE = 0x00000020;

    private static PineaLib lib;
    private static Map<String, SDLPineaImage> imageMap;

    static {
        // 设置jna库路径
        System.setProperty("jna.library.path", "csrc/bin");
        // 加载Pinea动态库
        lib = Native.load("Pinea", PineaLib.class);

        imageMap = new ConcurrentHashMap<>();
    }

    public static void pineaInit(String title, int width, int height) {
        lib.pineaInit(title, width, height);
    }

    public static void pineaQuit() {
        imageMap.forEach((k, v) -> {
            lib.pineaDropImage(v.imagePointer);
        });
        lib.pineaQuit();
    }

    public static void pineaShow() {
        lib.pineaShow();
    }

    public static boolean pineaPollEvent(PineaEvent event) {
        return lib.pineaPollEvent(event);
    }

    public static void pineaClear(PineaColor color) {
        lib.pineaClear(color);
    }

    public static void pineaRender() {
        lib.pineaRender();
    }

    public static void pineaFillRect(PineaRect rect, PineaColor color) {
        lib.pineaFillRect(rect, color);
    }

    public static PineaImage pineaLoadImage(String path) {
        SDLPineaImage sdlPineaImage = imageMap.computeIfAbsent(path, p -> {
            SDLPineaImage temp = new SDLPineaImage();
            lib.pineaLoadImage(path, temp);
            if (temp.imagePointer == Pointer.NULL) {
                throw new RuntimeException("加载图片: " + path + "失败");
            }
            return temp;
        });
        PineaRect region = new PineaRect(0, 0, sdlPineaImage.width, sdlPineaImage.height);
        return new PineaImage(sdlPineaImage.imagePointer, region);
    }

    public static void pineaDrawImage(PineaImage image, float x, float y) {
        PineaRect dstRect = new PineaRect(x, y,
                image.getWidth() * image.getScaleX(), image.getHeight() * image.getScaleY());
        lib.pineaDrawImage(image.getData(), image.getRegion(), dstRect, image.getAngle(), image.getFlip());
    }

}
